var express = require('express');
var router = express.Router();
var query = require("../db/db").query
/* 1. 引入上传图片模块 */
const multer = require("multer");
/* 2. 定已上传图片的文件 */
const upload = multer({
  dest: __dirname + "/../../uploads"
});
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});
//login 登陆时候post方法 
router.post("/login", function (req, res, next) {
  // console.log(req.body)
  let {
    username,
    password
  } = req.body
  let sql = "SELECT * from myshop.user where username=? and `password`=?"
  let values = [username, password]
  query(sql, values, function (err, results) {
    if (results.length === 0) {
      res.json({
        code: -1,
        message: "账号密码不正确",
        data: []
      })
    } else {
      req.session.user_id = results[0].user_id
      res.json({
        code: 1,
        message: "登陆成功",
        data: []
      })
    }
  })
  // res.json({
  //   code: 1,
  //   username,
  //   password,
  //   data: []
  // })
})

//上传图片的接口
router.post("/uploadImg", upload.single("file"), function (req, res, next) {
  const file = req.file;
  file.url = `${file.filename}`;
  res.send(file);
});

module.exports = router;